//
//  THBaseUtil.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "THBaseUtil.h"
#import <AdSupport/AdSupport.h>
#if defined(__IPHONE_14_0)
#import <AppTrackingTransparency/AppTrackingTransparency.h>//适配iOS14
#endif
#import "UIViewController+THCurretnVC.h"

@interface THBaseUtil()

@property (nonatomic,copy) NSString *idfaString;

@end

@implementation THBaseUtil

 
+ (void)load
{
    [THBaseUtil shareManager];
}

+ (THBaseUtil *)shareManager
{
    static dispatch_once_t onceToken;
    static THBaseUtil *_instanceManager = nil;
    dispatch_once(&onceToken, ^{
        _instanceManager = [[THBaseUtil alloc]init];
        [_instanceManager commit];
    });
    return _instanceManager;
}

- (void)commit
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getIdfaStr];
    });
}


+ (void)gotoWeiXin
{
    NSURL * url = [NSURL URLWithString:@"weixin://"];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
    //先判断是否能打开该url
    if (canOpen)
    {   //打开微信
        [[UIApplication sharedApplication] openURL:url];
    }else {
        [self showToast:@"您的设备未安装微信APP"];
    }
}

+ (NSString *)formatNumer:(NSInteger)number
{
    if (number <= 9999) {
        return [NSString stringWithFormat:@"%ld",number];
    }
    
    return [NSString stringWithFormat:@"%.1fW",floor(number/1000.0f)/10];
}

+ (NSString *)format2DotNumer:(NSInteger)number
{
    if (number <= 9999) {
        return [NSString stringWithFormat:@"%ld",number];
    }
    
    return [NSString stringWithFormat:@"%.2fW",floor(number/100.0f)/100];
}


/**
 * 金额的格式转化
 * str : 金额的字符串
 * numberStyle : 金额转换的格式
 * return  NSString : 转化后的金额格式字符串
 */
+ (NSString *)stringChangeMoneyWithStr:(NSString *)str
{
    
    // 判断是否null 若是赋值为0 防止崩溃
    if (([str isEqual:[NSNull null]] || str == nil)) {
        str = 0;
    }
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    // 注意传入参数的数据长度，可用double
    NSString *money = [formatter stringFromNumber:[NSNumber numberWithDouble:[str doubleValue]]];
    return money;
}

+ (UIColor *)colorWithHexString:(NSString *)string
{
    if (string.length <= 0) {
        return nil;
    }
    
    NSString *pureHexString = [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    NSString *resultHexString = pureHexString;
    if ([pureHexString hasPrefix:@"#"]) {
        resultHexString = [pureHexString substringFromIndex:1];
    } else if ([pureHexString hasPrefix:@"0x"]) {
        resultHexString = [pureHexString substringFromIndex:2];
    }
    //支持#fff,#ffff,#ffffff,#ffffffff， 0x...
    if (resultHexString.length < 3 || resultHexString.length == 5 || resultHexString.length == 7 || resultHexString.length > 8)
    {
        return nil;//不符合规则返回nil
//        return [UIColor whiteColor];
    }
    
    if (resultHexString.length < 6)
    {
        NSMutableArray *originColor = @[].mutableCopy;
        for (NSInteger i = 0; i < resultHexString.length; i++)
        {
            NSString *subStr = [resultHexString substringWithRange:NSMakeRange(i, 1)];
            [originColor addObject:subStr];
            [originColor addObject:subStr];
        }
        resultHexString = [originColor componentsJoinedByString:@""];
    }
    
    if (resultHexString.length == 6)
    {
        resultHexString = [NSString stringWithFormat:@"%@ff",resultHexString];
    }
    
    if (resultHexString.length != 8)
    {
        return [UIColor whiteColor];
    }
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [resultHexString substringWithRange:range];
    
    range.location += range.length ;
    NSString *gString = [resultHexString substringWithRange:range];
    
    range.location += range.length ;
    NSString *bString = [resultHexString substringWithRange:range];
    
    range.location += range.length ;
    NSString *aString = [resultHexString substringWithRange:range];
    
    unsigned int r, g, b, a;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    [[NSScanner scannerWithString:aString] scanHexInt:&a];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:((float) a/ 255.0f)];
}

///解析昵称扫光渐变色
+ (NSArray<UIColor *> *)nickNameScanColor:(NSString *)colorString
{
    NSArray <NSString *> *colorStrArray = [colorString componentsSeparatedByString:@"-"];
    NSMutableArray <UIColor *>*colorArray = @[].mutableCopy;
    for (NSString *colorStr in colorStrArray) {
        kArrayAddObj(colorArray, [self colorWithHexString:colorStr]);
    }
    return colorArray.copy;
}

+ (id)objectFromArray:(NSArray *)array atIndex:(NSInteger)index
{
    if ([array isKindOfClass:[NSArray class]] && array.count > index && index >= 0)
    {
        return array[index];
    }
    return nil;
}

/// 字符串转为颜色
/// @param string RGBA字符串rgba(0,0,0,0.2)
+ (UIColor *)colorWithRGBAString:(NSString *)string
{
    if (![string isKindOfClass:NSString.class] || string.length <= 0) {
        return nil;
    }
    
    if ([string hasPrefix:@"rgba"])
    {
        NSString *rgbaName = [string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"rgba() "]];
        NSArray *rgba = [rgbaName componentsSeparatedByString:@","];
        if ([rgba count] != 4)
        {
            // Incorrect syntax
            return nil;
        }
        CGFloat red = (CGFloat)[[rgba objectAtIndex:0] floatValue] / 255;
        CGFloat green = [[rgba objectAtIndex:1] floatValue] / 255;
        CGFloat blue = [[rgba objectAtIndex:2] floatValue] / 255;
        CGFloat alpha = [[rgba objectAtIndex:3] floatValue];
        return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    }
    
    if([string hasPrefix:@"rgb"])
    {
        NSString * rgbName = [string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"rbg() "]];
        NSArray* rgb = [rgbName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
        
        if ([rgb count] != 3)
        {
            // Incorrect syntax
            return nil;
        }
        
        CGFloat red = [[rgb objectAtIndex:0] floatValue] / 255;
        CGFloat green = [[rgb objectAtIndex:1] floatValue] / 255;
        CGFloat blue = [[rgb objectAtIndex:2] floatValue] / 255;
        CGFloat alpha = 1.0;
        
        return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    }
    
    if ([string hasPrefix:@"#"]||[string hasPrefix:@"0x"])
    {
        return [self colorWithHexString:string];
    }
    return nil;
}

+ (NSString *)formatMagGold:(long long )gold
{
    if (gold <= 0) {
        return @"0";
    }
    return [self formatMagpieGold:@(gold).stringValue];
}


+ (NSString *)formatMagpieGold:(NSString *)gold
{
    if ([gold isKindOfClass:NSNumber.class]) {
        gold = [NSString stringWithFormat:@"%@",gold];
    }
    if (gold.length <= 0) {
        return @"0";
    }else if (gold.length < 4){
        return gold;
    }else if (gold.length < 7){
        return [NSString stringWithFormat:@"%.1fK",[gold substringToIndex:gold.length - 2].doubleValue/10.0f];
    }else if (gold.length < 10){
        return [NSString stringWithFormat:@"%.1fM",[[gold substringToIndex:gold.length - 5] doubleValue]/10.0f];
    }else if (gold.length < 13){
        return [NSString stringWithFormat:@"%.1fB",[[gold substringToIndex:gold.length - 8] doubleValue]/10.0f];
    }else if (gold.length < 16){
        return [NSString stringWithFormat:@"%.1fT",[[gold substringToIndex:gold.length - 11] doubleValue]/10.0f];
    }else{
        return [NSString stringWithFormat:@"%.1fP",[[gold substringToIndex:gold.length - 14] doubleValue]/10.0f];
    }
}

+ (void)checkAndRoundCornerToView:(UIView *)view rect:(CGRect)rect corners:(UIRectCorner)corners radius:(CGFloat)radius
{
    NSString * tagString = [[NSString alloc] initWithFormat:@"%ld|%.1f",corners,radius];
    if (view.layer.mask != nil)
    {
        NSString * KTag = [view.layer.mask valueForKey:@"KTag"];
        if (CGRectEqualToRect(view.layer.mask.frame, rect) && [KTag isEqualToString:tagString])
        {
            return;
        }
    }
    CAShapeLayer * maskLayer = [self layerWithRoundedRect:rect byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    [maskLayer setValue:tagString forKey:@"KTag"];
    view.layer.mask = maskLayer;
}

+ (CAShapeLayer *)layerWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii
{
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:cornerRadii];
    CAShapeLayer * layer = [CAShapeLayer layer];
    layer.path = path.CGPath;
    return layer;
}

+ (void)gotoSystemAppConfig
{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url])
    {
        [[UIApplication sharedApplication] openURL:url];
    }
}

+ (void)gotoOutsideUrl:(NSString *)urlString
{
    if (![urlString isKindOfClass:NSString.class] || urlString.length <= 0) {
        return;
    }
    NSURL * url = [NSURL URLWithString:urlString];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
    if (canOpen)
    {
        [[UIApplication sharedApplication] openURL:url];
    }else{
        [self showToast:[NSString stringWithFormat:@"无法打开%@",urlString]];
    }
}

+ (UIImage *)zh_launchImage
{
    CGSize viewSize = CGSizeMake(MainScreenWidth(), MainScreenHeight());
    NSString *viewOrientation = @"Portrait";    //横屏请设置成 @"Landscape"
    NSString *launchImage = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImage = dict[@"UILaunchImageName"];
        }
    }
    
    if(launchImage.length > 0)
    {
        return [UIImage imageNamed:launchImage];
    }
    else
    {
        return nil;
    }
}

+ (UIImage *)imageFromView:(UIView *)view
{
    if ((id)view == [NSNull null] || ![view isKindOfClass:[UIView class]])
    {
        return nil;
    }
    [view layoutIfNeeded];
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (NSString *)hqFillImageURL:(NSString *)url width:(CGFloat)width height:(CGFloat)height quality:(NSInteger)quality
{
    if (url.length > 0 && ![url containsString:@"ignore=1"])
    {
        url = [url componentsSeparatedByString:@"?"].firstObject;
        url = [url stringByAppendingFormat:@"?x-oss-process=image/resize,m_fill,h_%d,w_%d,Q_%d",(int)height,(int)width,(int)quality];
    }
       
    return url;
}


/**
 查找子字符串在父字符串中的所有位置
 @param content 父字符串
 @param tab 子字符串
 @return 返回位置数组
 */
+ (NSMutableArray*)calculateSubStringCount:(NSString *)content str:(NSString *)tab {
    int location = 0;
    NSMutableArray *locationArr = [NSMutableArray new];
    NSRange range = [content rangeOfString:tab];
    if (range.location == NSNotFound){
        return locationArr;
    }
    //声明一个临时字符串,记录截取之后的字符串
    NSString * subStr = content;
    while (range.location != NSNotFound) {
        if (location == 0) {
            location += range.location;
        } else {
            location += range.location + tab.length;
        }
        //记录位置
        NSNumber *number = [NSNumber numberWithUnsignedInteger:location];
//        [locationArr addObject:number];
        //每次记录之后,把找到的字串截取掉
        subStr = [subStr substringFromIndex:range.location + range.length];
        NSLog(@"subStr %@",subStr);
        range = [subStr rangeOfString:tab];
        NSLog(@"rang %@",NSStringFromRange(range));
        [locationArr addObject:NSStringFromRange(range)];
    }
    return locationArr;
}

+ (UIImage *)imageFromWindow
{
    UIGraphicsBeginImageContextWithOptions([UIScreen mainScreen].bounds.size, YES, 0.0);
    [[THCurrentVCWindowsManager shareManager].currentWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}


+ (void)hqOpenSystemPage
{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

/// url加后缀，实现图片模糊
+ (NSString *)hqImgUrlAddBlur:(NSString *)url
{
    if (url.length <= 0) {
        return url;
    }
    
    if ([url containsString:@"x-oss-process=image/blur"]) {
        return url;
    }
    if ([url containsString:@"?"]) {
        url = [url stringByAppendingString:@"&"];
    }else{
        url = [url stringByAppendingString:@"?"];
    }
    return [url stringByAppendingString:@"x-oss-process=image/blur,r_50,s_50"];
}


/// 移除模糊后缀
/// @param url url 
+ (NSString *)hqImgUrlRemoveBlur:(NSString *)url
{
    if (url.length <= 0) {
        return url;
    }
    if (![url containsString:@"x-oss-process=image/blur"]) {
        return url;
    }
    return [url stringByReplacingOccurrencesOfString:@"x-oss-process=image/blur,r_50,s_50" withString:@""];
}

+ (UIImage *)tg_blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur
{
    if (image == nil) {
        return nil;
    }
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:ciImage forKey:kCIInputImageKey];
    //设置模糊程度
    [filter setValue:@(blur) forKey: @"inputRadius"];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef outImage = [context createCGImage: result fromRect:ciImage.extent];
    UIImage * blurImage = [UIImage imageWithCGImage:outImage];
    CGImageRelease(outImage);
    return blurImage;
}

+ (NSString *)hqImgUrlAddBlur:(NSString *)url width:(CGFloat)w height:(CGFloat)h
{
    if (url.length <= 0) {
        return url;
    }
    
    if ([url containsString:@"x-oss-process"]) {
        return url;
    }
    if ([url containsString:@"?"]) {
        url = [url stringByAppendingString:@"&"];
    }else{
        url = [url stringByAppendingString:@"?"];
    }
    url = [url stringByAppendingFormat:@"x-oss-process=image/resize,m_fill,h_%d/blur,w_%d,r_1,s_1",(int)h,(int)w];
    return url;
}


+ (NSString *)hqImgUrlAddBlur:(NSString *)url width:(CGFloat)w height:(CGFloat)h blurLevel:(NSInteger)blur
{
    if (url.length <= 0) {
        return url;
    }
    
    if ([url containsString:@"x-oss-process"]) {
        return url;
    }
    if ([url containsString:@"?"]) {
        url = [url stringByAppendingString:@"&"];
    }else{
        url = [url stringByAppendingString:@"?"];
    }
    url = [url stringByAppendingFormat:@"x-oss-process=image/resize,m_fill,h_%d/blur,w_%d,r_%d,s_%d",(int)h,(int)w,(int)blur,(int)blur];
    return url;
}

- (NSString *)idfaStr
{
    if (_idfaString.length <= 1) {
        return [self getIdfaStr];
    }
    return _idfaString;
}

- (NSString *)getIdfaStr
{
    __block NSString *idfa;
    if (@available(iOS 14.5, *)) {
        // iOS14及以上版本需要先请求权限
        ATTrackingManagerAuthorizationStatus status = ATTrackingManager.trackingAuthorizationStatus;
        if (status == ATTrackingManagerAuthorizationStatusNotDetermined) { //用户未做选择或未弹窗
            dispatch_semaphore_t sem = dispatch_semaphore_create(0);
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                // 获取到权限后，依然使用老方法获取idfa
                if (status == ATTrackingManagerAuthorizationStatusAuthorized) { //用户允许
                    idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                }
                dispatch_semaphore_signal(sem);
            }];
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        }else if(status == ATTrackingManagerAuthorizationStatusAuthorized){//用户允许
            idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
        }else{
            NSLog(@"请在设置-隐私-Tracking中允许App请求跟踪");

        }
    }else{
        idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
    }

    idfa = (idfa ? idfa : @"0");
    _idfaString = idfa;
    return _idfaString;
}


+ (UIImage*)downImage:(NSString*)imageUrl
        finishedBlock:(SDInternalCompletionBlock)complete;
{
    SDWebImageManager *webManager = [SDWebImageManager sharedManager];
    NSString *absoluteString = [webManager cacheKeyForURL:[NSURL URLWithString:imageUrl]];
    SDImageCache *imgCache = webManager.imageCache;
    UIImage *imagePic = [imgCache imageFromDiskCacheForKey:absoluteString];
    if(nil == imagePic)
    {
        if(complete)
        {
            [webManager loadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageDownloaderAllowInvalidSSLCertificates|SDWebImageDownloaderContinueInBackground|SDWebImageRetryFailed progress:nil completed:complete];
        }
        else
        {
            [[SDWebImagePrefetcher sharedImagePrefetcher]prefetchURLs:@[[NSURL URLWithString:imageUrl]]];
        }
    }
    
    return imagePic;
}

+ (BOOL)isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    if ([string isEqualToString:@"(null)"])
    {
        return YES;
    }
    return NO;
}

+(NSMutableDictionary *)getUrlParamsAsDict:(NSString *)url{
    
    NSMutableDictionary *parm = [[NSMutableDictionary alloc]init];
    //传入url创建url组件类
    NSURLComponents *urlComponents = [[ NSURLComponents alloc] initWithString:url ];
    //回调遍历所有参数，添加入字典
    [urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ( ![THBaseUtil isBlankString:obj.value ] && ![ THBaseUtil isBlankString: obj.name ]) {
            [parm setObject:obj.value forKey:obj.name];
        }
    }];
    return parm;
}


+(NSString *)checkUrlDomaim:(NSString *)url
{
    NSString *checkUrl;
    
    if ([url hasPrefix:@"http"] || [ url hasPrefix:@"https" ])
    {
        checkUrl = url ;
    }else if ([url hasPrefix:@"browsers"])
    {
        checkUrl =  [url stringByReplacingOccurrencesOfString:@"browsers" withString:@"https"];
    }else if ([url hasPrefix:@"browser"])
    {
        checkUrl =  [url stringByReplacingOccurrencesOfString:@"browser" withString:@"http"];
        
    }else if ([url hasPrefix:@"popup://"]){
        url = [url stringByReplacingOccurrencesOfString:@"popup://" withString:@"https://" ];
    }
    
    // 处理以&结尾的不正常的url
    if ([checkUrl hasSuffix:@"&"]) {
        checkUrl = [checkUrl stringByReplacingOccurrencesOfString:@"&" withString:@""];
    }
    
    return checkUrl;
}
+ (NSString *)WebURLEncodedString:(NSString *)url
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)url,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

@end
